﻿namespace Web.Control.Member.User
{
    using System;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Text.RegularExpressions;
    using Lx.Web.Common.UI;
    using Lx.Web.Common.ControlsUI;
    using System.Collections;
    using System.Xml;
    using System.Net;
    using System.IO;

    using BLF.WWW_User.Users;
    using Model.WWW_User.User;
    using System.Collections.Generic;
    using System.Text;
    using live;

    public class yahoo : BaseControl
    {
        /* ---------------------------- Windows Live ------------------------- */
        //Comma-delimited list of offers to be used.
        protected string Offers = System.Configuration.ConfigurationManager.AppSettings["Offers"].ToString();
        //Name of cookie to use to cache the consent token. 
        protected string AuthCookie = System.Configuration.ConfigurationManager.AppSettings["AuthCookie"];
        // Initialize the WindowsLiveLogin module.
        protected static readonly WindowsLiveLogin wll = new WindowsLiveLogin(true);
        protected WindowsLiveLogin.ConsentToken Token;
        protected string ConsentUrl;
        protected static readonly DateTime ExpireCookie = DateTime.Now.AddYears(-10);
        protected static readonly DateTime PersistCookie = DateTime.Now.AddYears(10);

        public StringBuilder emailBuilder = new StringBuilder();
        protected string bum;
        protected Repeater repmList;
        protected string memberno;
        protected List<InviteUserModel> mailList = new List<InviteUserModel>();
        protected List<InviteUserModel> su = new List<InviteUserModel>();
        protected string setp = "";

        protected override void OnLoad(EventArgs e)
        {
            if (HttpContext.Current.User.Identity.Name == "")
            {
                Page.Response.Redirect(LoginHost + "/User/login.htm?ReturnUrl=" + Page.Request.Url.AbsoluteUri);
            }
            memberno = HttpContext.Current.User.Identity.Name;
            string mo;
            bum = User.GetUserName(memberno, out mo);
            if (!string.IsNullOrEmpty(Request.QueryString["setp"]))
            {
                setp = Request.QueryString["setp"];
            }

            Page.Session["setp"] = null;
            Session["setp"] = "3";
            Response.Write("<script> var _EF_TList=new Array();</script>");
            //得到yahoo里面的联系人列表。
            if (!(string.IsNullOrEmpty(Request.QueryString["token"]) || string.IsNullOrEmpty(Request.QueryString["appid"]) || string.IsNullOrEmpty(Request.QueryString["sig"])))
            {


                //定义参数。
                string token = Request.QueryString["token"];
                string appid = Request.QueryString["appid"];
                TimeSpan t = DateTime.Now.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
                string ts = ((long)t.TotalSeconds).ToString();
                string sig = Enctype(string.Format("/WSLogin/V1/wspwtoken_login?appid={0}&token={1}&ts={2}{3}", appid, token, ts, "f6f4e4a7bc94b2ccab71e980a9739fdc"));
                string url = string.Format("https://api.login.yahoo.com/WSLogin/V1/wspwtoken_login?appid={0}&token={1}&ts={2}&sig={3}", appid, token, ts, sig);


                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
                Stream receiveStream = httpWebRequest.GetResponse().GetResponseStream();
                StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
                string txt = readStream.ReadToEnd();
                string cookie = "";
                string WSSID = "";

                Regex reg = new Regex("<Cookie>([\\s\\S]*?)</Cookie>", RegexOptions.Compiled);
                Match m = reg.Match(txt);
                if (m.Success) cookie = m.Groups[1].Value;

                reg = new Regex("<WSSID>([\\s\\S]*?)</WSSID>", RegexOptions.Compiled);
                m = reg.Match(txt);
                if (m.Success) WSSID = m.Groups[1].Value;

                WebClient client = new WebClient();
                client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";
                client.Encoding = Encoding.UTF8;
                client.Headers[HttpRequestHeader.Cookie] = cookie;
                string result = client.DownloadString(string.Format("http://address.yahooapis.com/v1/searchContacts?format=xml&fields=all&appid={0}&WSSID={1}", appid, WSSID));
                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(result.Substring(result.IndexOf(".dtd\">") + 6));
                XmlNodeList contactList = xDoc.SelectNodes("//search-response/contact");



                if (contactList != null)
                {
                    for (int i = 0; i < contactList.Count; i++)
                    {
                        InviteUserModel us = new InviteUserModel();
                        XmlNode nodeYahooID = contactList[i].SelectSingleNode("yahooid");
                        if (nodeYahooID != null)
                        {
                            XmlNode nodeName = contactList[i].SelectSingleNode("name");
                            if (nodeName != null && nodeName.InnerText.Length > 0)
                                us.Nickname = nodeName.InnerText;
                            us.MemberCrtNo = nodeYahooID.InnerText + (nodeYahooID.InnerText.Contains("@") ? "" : "@yahoo.com");
                        }
                        else
                        {
                            XmlNode nodeEmail = contactList[i].SelectSingleNode("email");
                            if (nodeEmail != null)
                            {
                                XmlNode nodeName = contactList[i].SelectSingleNode("name");
                                if (nodeName != null && nodeName.InnerText.Length > 0)
                                    us.Nickname = nodeName.InnerText;
                                us.MemberCrtNo = nodeEmail.InnerText;
                            }
                            else
                            {
                                XmlNode nodeOtherID = contactList[i].SelectSingleNode("otherid");
                                if (nodeOtherID != null)
                                {
                                    XmlNode nodeName = contactList[i].SelectSingleNode("name");
                                    if (nodeName != null && nodeName.InnerText.Length > 0)
                                        us.Nickname = nodeName.InnerText;
                                    us.MemberCrtNo = nodeOtherID.InnerText;
                                }
                            }
                        }
                        if (string.IsNullOrEmpty(us.Nickname) || us.Nickname.Trim().Length == 0) us.Nickname = us.MemberCrtNo.Split('@')[0];
                        us.MemberNo = us.MemberCrtNo;
                        mailList.Add(us);
                    }

                }

            }
            else {
                //读取MSV里面保存的cookie得到联系人列表
                if (Request.QueryString["method"] == "live1")
                {
                    //Get the consent URL for the specified offers.
                    ConsentUrl = wll.GetConsentUrl(Offers);

                    HttpRequest req = HttpContext.Current.Request;
                    HttpCookie authCookie = req.Cookies[AuthCookie];

                    //跳转到ms live的登陆页，进行身份验证获取token
                    if (Request.QueryString["action"] == "login")
                    {
                        if (authCookie != null)
                        {
                            authCookie.Expires = DateTime.Now.AddDays(-1);
                            Response.Cookies.Add(authCookie);
                        }
                        Response.Redirect(ConsentUrl);
                    }
                }
                if (Request.QueryString["intlid"] != null && Request.QueryString["token"] != null)
                {

                    long intlid = Int64.Parse(Request.QueryString["intlid"]);
                    WebRequest wrq =
                            WebRequest.Create(
                                string.Format(
                                    "https://livecontacts.services.live.com/users/@C@{0}/rest/invitationsbyemail", intlid));
                    wrq.Headers.Add("Authorization", string.Format("DelegatedToken dt=\"{0}\"", Request.QueryString["token"]));

                    WebResponse wrp = wrq.GetResponse();
                    string result;
                    using (StreamReader sr = new StreamReader(wrp.GetResponseStream()))
                    {
                        result = sr.ReadToEnd();
                    }
                    if (result != null)
                    {
                        XmlDocument xDoc = new XmlDocument();
                        xDoc.LoadXml(result);
                        XmlNodeList contactlist = xDoc.SelectNodes("//LiveContacts/Contacts/Contact");
                        StringBuilder contactsbulder = new StringBuilder();
                        if (contactlist != null)
                            for (int i = 0; i < contactlist.Count; i++)
                            {
                                InviteUserModel us = new InviteUserModel();
                                us.MemberCrtNo = contactlist[i].SelectSingleNode("PreferredEmail").InnerText;
                                us.Nickname = contactlist[i].SelectSingleNode("Profiles/Personal").InnerText;
                                if (us.Nickname.Length <= 0)
                                    us.Nickname = us.MemberCrtNo.Substring(0, us.MemberCrtNo.IndexOf('@'));
                                us.MemberNo = us.MemberCrtNo;
                                mailList.Add(us);
                            }
                    }
                }
            }
            if (mailList != null)
            {
                su = BLF.WWW_User.Users.User.GetUserList(mailList);
                foreach (InviteUserModel um in su)
                {
                    for (int i = 0; i < mailList.Count; i++)
                    {
                        if (mailList[i].MemberCrtNo == um.MemberCrtNo)
                        {
                            mailList.RemoveAt(i);
                        }
                    }
                }

                su.AddRange(mailList);
            }
            if (su != null)
            {
                Response.Write("<script> ");
                for (int i = 0; i < su.Count; i++)
                {
                    Response.Write("_EF_TList[" + i + "]='" + su[i].MemberNo + "';");
                }
                Response.Write("</script> ");
            }
            if (repmList != null)
            {
                repmList.DataSource = su;
                repmList.DataBind();
            }
            base.OnLoad(e);
        }

        public String Enctype(String chars)
        {
            string str = "";
            if (chars == "" || chars.Length < 1) return str;
            str = FormsAuthentication.HashPasswordForStoringInConfigFile(chars, "md5");
            return str == null ? null : str.ToLower();
        }

    }
}
